package com.oahcfly.chgame.core.script;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.utils.Array;
import com.oahcfly.chgame.core.mvc.CHActor;
import com.oahcfly.chgame.core.mvc.CHScreen;

/**
 * 
 * 脚本
 * 
 * @author haocao
 *
 */
public class CHScript implements IScript {

	private Array<String> stepArr = new Array<String>();

	private CHScreen parentScreen;

	private CHActor actor;

	public CHScript(CHScreen screen) {
		this.parentScreen = screen;
		actor = new CHActor();
	}

	@Override
	public void run(final Runnable callBackRunnable) {

		// 调用screen内，一系列的方法名。method1，mthod2，method3...
		this.parentScreen.addActor(actor);

		SequenceAction sequenceAction = new SequenceAction();
		for (int i = 0, size = stepArr.size; i < size; i++) {
			final String methodName = stepArr.get(i);
			RunnableAction runnableAction = new RunnableAction() {

				@Override
				public void run() {
					invokeMethod(methodName);
				}

			};
			sequenceAction.addAction(runnableAction);
		}

		sequenceAction.addAction(Actions.run(new Runnable() {

			@Override
			public void run() {
				parentScreen.removeActor(actor);
				CHScript.this.stepArr.clear();
				callBackRunnable.run();
			}
		}));
		actor.addAction(sequenceAction);

	}

	private void invokeMethod(String methodName) {

		final Class<?> screenClass = parentScreen.getClass();
		Method method;
		try {
			method = screenClass.getDeclaredMethod(methodName);
			method.invoke(parentScreen);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			Gdx.app.error(getClass().getSimpleName(), e.getLocalizedMessage());
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			Gdx.app.error(getClass().getSimpleName(), e.getLocalizedMessage());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			Gdx.app.error(getClass().getSimpleName(), e.getLocalizedMessage());
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			Gdx.app.error(getClass().getSimpleName(), e.getLocalizedMessage());
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			Gdx.app.error(getClass().getSimpleName(), e.getLocalizedMessage());
		}
	}

	/**
	 * 方法需要public。
	 */
	@Override
	public void addSteps(String... args) {
		for (String methodName : args) {
			stepArr.add(methodName);
		}
	}
}
